package com.ysj.aipicturebe.manager.sharding;


import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;

/**
 * 图片分表算法
 */
public class PictureShardingAlgorithm implements StandardShardingAlgorithm<Long> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> preciseShardingValue) {
        Long spaceId = preciseShardingValue.getValue(); // 获取分片键值（spaceId）
        String logicTableName = preciseShardingValue.getLogicTableName(); // 逻辑表名（picture）
        // 如果 spaceId 为 null，则路由到默认逻辑表（picture）
        if (spaceId == null) {
            return logicTableName;
        }

        // 生成目标分表名（如 picture_123）
        String realTableName = "picture_" + spaceId;

        // 检查分表是否存在，存在则路由到分表，否则回退到逻辑表
        if (availableTargetNames.contains(realTableName)) {
            return realTableName;
        } else {
            return logicTableName;
        }
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {
        return new ArrayList<>();
    }

    @Override
    public Properties getProps() {
        return null;
    }

    @Override
    public void init(Properties properties) {

    }
}